package com.snoweagle.core;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

//@Component
@Aspect
public class LogAspect {

    @Pointcut("@annotation(com.snoweagle.core.OperationLog)")
    public void PoCut(){}

    @Autowired
    private LogService logService;
    @Autowired
    private LogProtperties logProtperties;

    @Around("PoCut()")
    public Object saveLog(ProceedingJoinPoint joinPoint){
        try {
            long start = System.currentTimeMillis();
            Object proceed = joinPoint.proceed();//继承执行被切的方法，这里就是hello()方法
            long end = System.currentTimeMillis();
            String packages = logProtperties.getPackages();
            String toPackages = joinPoint.getTarget().getClass().getPackage().getName();
            boolean b = isNeedSave(packages,toPackages);
            if(b){
                //获取操作方法
                String methodName = joinPoint.getSignature().toLongString();
                //获取操作的方法
                Method[] methods = joinPoint.getTarget().getClass().getMethods();
                String operate = "";
                for (Method m : methods) {
                    if(m.toString().equals(methodName)){
                        OperationLog operationLog = m.getDeclaredAnnotation(OperationLog.class);
                        operate = operationLog.operate();
                        break;
                    }
                }

                Log log = new Log();
                log.setTime(end-start);
                log.setArgs(joinPoint.getArgs());
                log.setMethod(methodName.toString());
                log.setOperate(operate);
                log.setUsername(logService.getCurrentName().toString());
                logService.saveLog(log);
            }

            return proceed;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    private boolean isNeedSave(String packages, String toPackages) {
        if(packages == null )
            return true;
        String[] split = packages.split(",");
        for (String s : split) {
            toPackages.contains(s);
            return true;
        }
        return false;
    }

}
